﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;

namespace SolidPrinciples.LiskovSubstitution
{
    public class Container<T> : IEnumerable<T>
    {
        protected readonly List<T> _items = new List<T>();

        public IEnumerator<T> GetEnumerator()
        {
            return _items.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public virtual void Add(T item)
        {
            _items.Add(item);
        }

        public virtual void Remove(T item)
        {
            _items.Remove(item);
        }

        public virtual bool Contains(T item)
        {
            return _items.Contains(item);
        }
    }

    [TestFixture]
    public class ContainerClient
    {
        private Container<int> _container;

        [SetUp]
        public void Init()
        {
            _container = new Container<int>();
        }

        [Test]
        public void AddItem()
        {
            _container.Add(1);
            _container.Add(2);
            Assert.That(_container.ToArray(), Is.EquivalentTo(new[] {1, 2}));
        }
    }

    #region Step 1

    /*
     * A developer has given a task to introduce a persistent version of Container.
     * He found a third-party container implementation and then derived a new PersistentContainer class from Container, 
     * overrides Add method, and casts an item to PersistentItem
     * Test would not work.
     * 
     * There is a violation: when we replace  _container = new Container<int>(); with  _container = new PersistentContainer<int>(); in the test, then we will have AddItem test broken
     */

    public class PersistentContainer<T> : Container<T>
    {
        private readonly ThirdPartyPersistentContainer _container = new ThirdPartyPersistentContainer();

        public override void Add(T item)
        {
            base.Add(item);
            object persistentItem = item;
            _container.Add((PersistentObject) persistentItem);
        }
    }

    #region ThirdPartyPersistentContainer

    internal class ThirdPartyPersistentContainer
    {
        public void Add(PersistentObject item)
        {
        }
    }

    internal class PersistentObject
    {
    }

    #endregion


    #endregion
}